package com.yuexi.anotation.aspect;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zenx.cqe.PageQuery;
import com.zenx.dto.DataTableResponse;
import com.zenx.dto.SingleResponse;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * 自动设置请求头中的值到参数中
 *
 * @author jie
 * @date 2022/9/26 -20:29
 */
@Aspect
@Component
public class AutoPageAspect {

    @Pointcut("@annotation(com.yuexi.anotation.AutoPage)")
    public void pointcut() {
    }


    /**
     * 从请求头获取字段并设置到controller 请求参数中去，只支持对象作为入参
     */
    @Around("pointcut()")
    public SingleResponse around(ProceedingJoinPoint point) throws Throwable {
        // 获取分页参数
        Object[] args = point.getArgs();
        PageQuery pageQuery = (PageQuery) args[0];
        if (null == pageQuery || null == pageQuery.getLimit() || null == pageQuery.getOffset()) {
            throw new RuntimeException("参数无效");
        }
        // 使用PagerHelper进行分页
        Page<Object> page = PageHelper.offsetPage(pageQuery.getOffset(), pageQuery.getLimit());
        Object proceed = point.proceed();
        // 提取出data数据
        SingleResponse response = (SingleResponse) proceed;
        // 对返回结果进行包装
        return SingleResponse.success(new DataTableResponse<>(page.getTotal(), response.getResult()));
    }

}
